﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Taurus.Master.DTO;
using HtmlAgilityPack;
using Taurus.Platform.Net;
using System.IO;
using Newtonsoft.Json.Linq;

namespace Taurus.Master.BLL
{
    class Master
    {
        #region event
        public event EventHandler<PKEventArgs> StartPK;
        public event EventHandler<PKEventArgs> EndPK;
        #endregion

        #region field

        private PKer _pker;
        private const string PK_INDEX_URL = "http://www.kaixin001.com/!pker/index.php";
        private const string PK_STARTPK_URL = "http://www.kaixin001.com/!pker/!startpk.php?fuid={0}";
        private const string PK_SELKONGFU_URL = "http://www.kaixin001.com/!pker/!selkungfu.php";
        private const string PK_DONEPK_URL = "http://www.kaixin001.com/!pker/!dopk.php?fuid={0}&pkid={1}&flag=0&kfid={2}";

        #endregion

        #region construction

        public Master(PKer pker)
        {
            _pker = pker;
            Friends = new List<PKer>();
        }

        #endregion

        #region property

        public string StatusMessage
        {
            get
            {
                return _pker.Message;
            }
        }

        public string Level
        {
            get
            {
                return _pker.Level;
            }
        }

        public List<PKer> Friends
        {
            get;
            private set;
        }

        public string Winning
        {
            get
            {
                return _pker.Winning;
            }
        }

        private string KongfuID
        {
            get
            {
                return _pker.Kongfus[_pker.Kongfus.Count - 1].ID;
            }
        }
        #endregion

        #region public method

        public void UpdateInfo()
        {
            HtmlDocument doc = Util.AccessPage(_pker, PK_INDEX_URL);
            string s = doc.DocumentNode.SelectSingleNode("id('r2_2')/div[3]/div[1]/div[4]").InnerText;
            s = s.Substring(s.IndexOf("\t"));
            MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(s));
            StreamReader sr = new StreamReader(ms);

            _pker.Level = sr.ReadLine().Trim();
            string t = sr.ReadLine().Trim();
            _pker.Winning = sr.ReadLine().Trim();
            sr.Close();
            _pker.Message = doc.DocumentNode.SelectSingleNode("id('learntip')").InnerText.Trim();

            if (doc.DocumentNode.SelectNodes("id('friendinfo')/dd")!=null)
            {
                foreach (var node in doc.DocumentNode.SelectNodes("id('friendinfo')/dd"))
                {
                    PKer p = new PKer();
                    p.Level = node.SelectSingleNode("./div/span").InnerText;
                    p.UID = Util.GetNumber(node.SelectSingleNode("./div/a").Attributes["href"].Value).ToString();
                    p.Name = node.SelectSingleNode("./div/a").InnerText;
                    string temp = node.SelectSingleNode("./div[2]/img").Attributes["src"].Value;
                    if (temp.Contains("icon_teacher1"))
                    {
                        _pker.TeachersUID.Add(p.UID);
                    }
                    else if (temp.Contains("icon_disciple"))
                    {
                        _pker.ApprenticeUID.Add(p.UID);
                    }
                    else
                    {
                        //徒弟与师傅不被添加到被PK对象内
                        _pker.PKers.Add(p);
                    }
                    Friends.Add(p);
                    
                }
            }
            doc = Util.AccessPage(_pker, PK_SELKONGFU_URL);
            foreach (var node in doc.DocumentNode.SelectNodes("//li"))
            {
                Kongfu kf = new Kongfu();
                kf.ID = node.SelectSingleNode("./input").Attributes["value"].Value;
                kf.Name = node.InnerText.Trim();
                _pker.Kongfus.Add(kf);
            }
        }
        /// <summary>
        /// 返回身份
        /// </summary>
        /// <param name="pker"></param>
        /// <returns></returns>
        public TypeEnum GetTypeEnum(PKer pker)
        {
            if (_pker.TeachersUID.Contains(pker.UID))
            {
                return TypeEnum.Teacher;
            }
            else if (_pker.ApprenticeUID.Contains(pker.UID))
            {
                return TypeEnum.Apprentice;
            }
            else
            {
                return TypeEnum.Empty;
            }
        }

        public void PK()
        {
            foreach (var item in _pker.PKers.OrderBy(p => Util.GetNumber(p.Level)))
            {
                if (StartPK != null)
                {
                    StartPK(_pker, new PKEventArgs() { Pker = item });
                }
                HtmlDocument doc = Util.AccessPage(_pker, string.Format(PK_STARTPK_URL, item.UID));
                int pkid = GetPKID(doc.DocumentNode.InnerText);
                if (pkid!=0 && pkid!=1)
                {
                   
                    //DO PK
                    doc = Util.AccessPage(_pker, string.Format(PK_DONEPK_URL, item.UID, pkid, KongfuID));
                   
                }
                else if (pkid == 1)
                {
                    if (EndPK != null)
                    {
                        EndPK(_pker, new PKEventArgs() { Pker = item, ResultJson = doc.DocumentNode.InnerText });
                    }
                    break;
                }
                if (EndPK != null)
                {
                    EndPK(_pker, new PKEventArgs() { Pker = item, ResultJson = doc.DocumentNode.InnerText });
                }
            }
        }

        #endregion

        #region private method

        /// <summary>
        /// if can't pk return 1 or 0
        /// 1 wait 6 hour
        /// </summary>
        /// <param name="json"></param>
        /// <returns></returns>
        private int GetPKID(string json) 
        {
            if (json == string.Empty)
            {
                return 0;
            }
            JObject jo = JObject.Parse(json);
            if (jo["pkid"] == null)
            {
                return jo["r"].Value<int>() == 1 ? 1 : 0;
            }
            else
            {
                return jo["pkid"].Value<int>();
            }
        }

        #endregion


    }
}
